from django.forms.models import ModelForm, ModelChoiceField
from classificados.models import Anuncio, SubCategoria, Usuario,\
    Categoria
from classificados.models import TIPO_CHOICES
#from warnings import catch_warnings
#from django.contrib.messages.constants import ERROR
from django.contrib.localflavor.br.forms import BRCPFField, BRZipCodeField,\
    BRPhoneNumberField
#from PIL import Image
#from Classi180.settings import MEDIA_ROOT
from django import forms
from django.forms.widgets import *
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
from Classi180.classificados.models import Cidade

class HorizRadioRenderer(forms.RadioSelect.renderer):
    def render(self):
        return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))


class UsuarioForm(ModelForm):
    class Meta:
        model = Usuario
        exclude = ('user', 'thumbnail','status','dataCadastro','quantidadeAcesso')
    
    nome = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class':'validate[required] input-large'}))
    cpf = BRCPFField(widget=forms.TextInput(attrs={'class':'validate[required] input-small cpf'}))
    telefone = BRPhoneNumberField(widget=forms.TextInput(attrs={'class':'validate[required] input-small tel'}))
    cep = BRZipCodeField(widget=forms.TextInput(attrs={'class':'validate[required] input-small cep'}))
    cidade = forms.ModelChoiceField(queryset=Cidade.objects.all(), widget = forms.Select())
    foto = forms.ImageField(required=False, widget=FileInput(attrs={'class':'botao-padrao'}))
    email = forms.EmailField(max_length=255, widget=forms.TextInput(attrs={'class':'input-medium validate[required]'}))
    senha  = forms.CharField(max_length = 30, widget = forms.PasswordInput(attrs={'class':'required input-medium validate[required]','minlength':'5'}))
    def clean_email(self):
        if User.objects.filter(
            email=self.cleaned_data['email'],
            ).count():
            raise forms.ValidationError('Ja existe um usuario com este e-mail')

        return self.cleaned_data['email']
    def save(self, commit=False, force_inert=True, force_update=True):
        if not self.instance.id:
            emailRegistrado = Usuario.objects.filter(email = self.instance.email).count()
            if emailRegistrado:
                emailExistente = emailRegistrado

            usr = Usuario.objects.filter(email = self.instance.email)

            if usr:
                u = usr[0]
            else:
                u = User.objects.create_user(self.instance.email, self.instance.email, self.instance.senha)

            u.is_active = False
            u.save()
            self.instance.user = u
        else:
            self.instance.user.username = self.instance.email
            self.instance.user.email = self.instance.email
            self.instance.user.set_password(self.instance.senha)
            self.instance.user.is_active = False
            self.instance.user.save()
        usuario = super(UsuarioForm, self).save()
  
        if commit:
            usuario.save()
  
        return usuario

class CadastroForm(forms.ModelForm):
    class Meta:
        model = Anuncio
        exclude = ('usuario','cidade','thumbnail','tags','dataCadastro','dataSaida','status','quantidadeAcesso','quantidadeFoto')
    
    categoria = forms.ModelMultipleChoiceField(queryset=Categoria.objects.all(), widget=SelectMultiple(attrs={'margin-left':'0', 'margin-right':'10px','size':'11'}))
    subcategoria = forms.MultipleChoiceField(widget=SelectMultiple(attrs={'class':'last','margin-right':'0','size':'11'}))    
    tipo = forms.ChoiceField(widget=RadioSelect(renderer=HorizRadioRenderer, attrs={'class':'tip'}), choices=TIPO_CHOICES)
    descricao = forms.CharField(max_length=60, widget=forms.TextInput(attrs={'class':'titulo_anun'}))
    preco = forms.FloatField(required=False, widget=forms.TextInput(attrs={'class':'preco_anun'}))
    foto = forms.ImageField(required=False, widget=FileInput(attrs={'class':'botao-padrao','multiple':'true'}))
    video = forms.URLField(required=False, widget=forms.TextInput(attrs={'class':'video_anun','value':'Youtube URL'}))
    detalhes = forms.CharField(required=False, widget=forms.Textarea())
    
    def save(self, commit=False, force_inert=True, force_update=True):
        anuncioNovo = super(CadastroForm, self).save()
  
        if commit:
            anuncioNovo.save()
  
        return anuncioNovo
  
    
    
class AnuncioForm(ModelForm):
    class Meta:
        model = Anuncio
      
    def __init__(self, *args, **kwargs):
        super(AnuncioForm, self).__init__(*args, **kwargs)
        self.fields['detalhes'].widget = forms.Textarea()
        self.fields['subcategoria'].queryset = SubCategoria.objects.filter(categoria__in=self.fields['categoria'].queryset)
        
#        cep = ModelChoiceField.l
#        cat = SubCategoria.objects.filter(categoria=self.initial['categoria'])
#d        self.fields['subcategoria'].queryset = cat.id
        if self.instance.id:
            if self.instance.categoria:
                subcategorias = SubCategoria.objects.filter(categoria__exact = self.instance.categoria )
                subcategoria__field = self.fields['subcategoria'].widget
                subcategoria__choices = []
                subcategoria__choices.append(('','----'))
                for objSubcategoria in subcategorias:
                    subcategoria__choices.append((objSubcategoria.id,objSubcategoria.nome))
                    subcategoria__field.choices = subcategoria__choices
        #else:
            #self.fields['subcategoria'].queryset = SubCategoria.objects.filter(categoria__exact = self.fields['categoria'].prepare_value(self))
""" def save_model(self, *args, **kwargs):
        ""Metodo declarado para criar miniatura da imagem depois de salvar
        DEVO VOLTAR AQUI MAIS TARDE""
        imagem = super(AnuncioForm, self).save_model(*args, **kwargs)

        if 'foto' in self.changed_data:
            extensao = imagem.foto.name.split('.')[-1]
            imagem.thumbnail = imagem.foto.name+'/%d.%s'%(imagem.id, extensao)

            miniatura = Image.open(imagem.foto.path)
            #MEDIA_ROOT+'/anuncio/'+str(imagem.categoria.id)+'/'+str(imagem.subcategoria.id)
            miniatura.thumbnail((150,100), Image.ANTIALIAS)
            miniatura.save(imagem.thumnail.path)

            imagem.save()

        return imagem"""